package com.vctgo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vctgo.system.domain.Chinas;
import com.vctgo.system.mapper.ChinasMapper;
import com.vctgo.system.service.ChinasService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: chuaimingyu
 * @date: 2024/12/18 19:56
 **/
@Service
@Transactional
public class ChinasServiceImpl extends ServiceImpl<ChinasMapper, Chinas> implements ChinasService {


    @Autowired
    private ChinasMapper chinasMapper;


    @Override
    public List<Chinas> getRegions() {
        // 全部省数据
        List<Chinas> chinas = chinasMapper.selectList(new QueryWrapper<Chinas>().eq("pid", 0L).eq("level", "1"));

        List<Long> pid = new ArrayList<>();
        chinas.forEach(item -> {
            pid.add(item.getCode());
        });
        //全部市数据
        List<Chinas> json1 = chinasMapper.selectList(new QueryWrapper<Chinas>().eq("level", "2").in("pid", pid));
        Map<Long,List<Chinas>> cdv=json1.stream().collect(Collectors.groupingBy(Chinas::getPid));

        chinas.stream().forEach(a ->a.setChildren(cdv.get(a.getCode())));

        List<Long> pid1=new ArrayList<>();
        json1.forEach(item ->{
            pid1.add(item.getCode());
        });
        //全部县 区数据
        List<Chinas> json2=chinasMapper.selectList(new QueryWrapper<Chinas>().eq("level","3").in("pid",pid1));
        Map<Long,List<Chinas>> cdv2=json2.stream().collect(Collectors.groupingBy(Chinas::getPid));
        chinas.stream().filter(a -> a.getChildren() != null).forEach(a -> a.getChildren().stream()
                .forEach(i -> i.setChildren(cdv2.get(i.getCode()))));

        return chinas;

    }
}
